<template>
  <!-- 异常设置 -->
  <div class="app-container-add">
    <!-- 功能按钮 -->
    <el-row :gutter="10" class="button-wrap" :style="{width:mainContentWidth + 'px','left':'80px'}">
      <el-col :span="1.5">
        <el-button v-clickForbidden :disabled="edited" icon="el-icon-document-checked" size="middle" @click="handleSave">保存</el-button>
      </el-col>
    </el-row>
    <!-- form表单 -->
    <div class="main-content">
      <el-card class="box-card" shadow="never" ref="mainContent">
        <div slot="header" class="clearfix">
          <span>异常设置</span>
        </div>
        <div class="main-content-body">
          <el-row :gutter="20" class="content">
            <el-col :span="14">
              <el-table
                ref="multipleTable"
                :data="tableData"
                style="width: 100%;"
                stripe
                :span-method="objectSpanMethod"
                class="table-list"
              >
                <el-table-column prop="typeName" label="设备类型" min-width="120" align="center" :show-overflow-tooltip="true" />
                <el-table-column prop="landName" label="地貌类型" min-width="120" align="center" :show-overflow-tooltip="true" />
                <el-table-column prop="maxWorkload" label="速度" min-width="120" align="center" :show-overflow-tooltip="true">
                  <template slot-scope="{row}">
                    <el-input v-if="row.isEdit" v-model="row.maxWorkload" size="size" />
                    <span v-else>{{ row.maxWorkload }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="workloadUnit" label="单位" min-width="120" align="center" :show-overflow-tooltip="true">
                  <template slot-scope="{row}">

                    <el-select v-if="row.isEdit" v-model="row.workloadUnit" size="small" placeholder="">
                      <el-option
                        v-for="item in workloadUnitOptions"
                        :key="item.dictValue"
                        :label="item.dictLabel"
                        :value="item.dictValue"
                      />
                    </el-select>
                    <span v-else>{{ maxWorkload(row.workloadUnit) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center" :show-overflow-tooltip="true">
                  <template slot-scope="{row,$index}">
                    <el-button v-if="!row.isEdit" size="mini" plain type="primary" @click="handleEdit(row,$index)">编辑</el-button>
                    <el-button v-if="row.isEdit" size="mini" plain @click="handleCancel($index)">取消</el-button>
                    <el-button v-if="row.isEdit" size="mini" plain type="success" @click="handleAdd(row)">保存</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="10">
              <el-form ref="formData" class="dataForm" :rules="rules" :model="formData" label-width="110px">
                <div class="data-form-item">
                  <el-row :gutter="20">
                    <el-col :lg="24">
                      <el-form-item label="" prop="location">
                        <template slot="label">
                          <span class="labelTitle">位置偏差</span>
                        </template>
                        <el-input v-model="formData.location" placeholder="请输入位置偏差" />
                      </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                      <el-form-item label="" prop="locationUnit">
                        <template slot="label">
                          <span class="labelTitle">位置偏差单位</span>
                        </template>
                        <el-select
                          v-model="formData.locationUnit"
                          size="small"
                          clearable
                          placeholder="请选择位置偏差单位"
                        >
                          <el-option
                            v-for="dict in locationOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                      <el-form-item label="" prop="minTime">
                        <template slot="label">
                          <span class="labelTitle">时间偏差</span>
                        </template>
                        <el-input v-model="formData.minTime" clearable placeholder="请输入时间偏差" />
                      </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                      <el-form-item label="" prop="timeUnit">
                        <template slot="label">
                          <span class="labelTitle">时间偏差单位</span>
                        </template>
                        <el-select
                          v-model="formData.timeUnit"
                          size="small"
                          filterable
                          placeholder="请选择时间偏差单位"
                          clearable
                        >
                          <el-option
                            v-for="dict in timeOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :lg="24">
                      <el-form-item label="" prop="versionNum">
                        <template slot="label">
                          <span class="labelTitle" v-html="`版&ensp;本&ensp;号`" />
                        </template>
                        <el-input v-model="formData.versionNum" readonly placeholder="请输入版本号" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </el-form>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
// 页面接口
import { addException, getVersionNum, speedConfig } from '@/api/superviseBaseInfo/exception'
import { dataMethod } from '@/utils/tableObjectSpanMethod.js'
// 字段校验
import { validateDouble } from '@/utils/validate'
import person from '@/assets/image/person.png'
// 系统字典
import { getSysDicts } from '@/api/common/getSysDicts' // 查询字典类行中的数据
export default {
  components: {
  },
  data() {
    return {
      mainContentWidth: '',
      // 单位类型
      workloadUnitOptions: [],
      tableDataOld: [],
      tableData: [], // 速度配置
      person,
      locationOptions: [], // 位置偏差单位
      timeOptions: [], // 时间偏差单位
      speedOptions: [], // 速度偏差单位
      title: '', // 页面标题
      /* 表单 start*/
      formDataOld: {},
      formData: {
        location: '', // 位置偏差y
        locationUnit: '', // 位置偏差单位
        timeUnit: '', // 时间偏差单位
        minTime: '',
        versionNum: ''
      },
      rules: { // 表单验证提示
        location: [
          { required: true, message: '位置偏差不得为空', trigger: 'blur' },
          { required: true, validator: validateDouble }
        ],
        locationUnit: [
          { required: true, message: '位置偏差单位不得为空', trigger: 'blur' }
        ],
        minTime: [
          { required: true, message: '时间偏差不得为空', trigger: 'blur' },
          { required: true, validator: validateDouble }
        ],
        timeUnit: [
          { required: true, message: '时间偏差单位不得为空', trigger: 'blur' }
        ]
      },
      spanObj: {},
      cloneRow: {},
      edited: true // 数据修改后按钮才可用
      /* 表单 end*/
    }
  },
  computed: {
    maxWorkload() {
      return (maxWorkload) => this.selectDictLabel(this.workloadUnitOptions, maxWorkload)
    }
  },
  watch: {
    formData: {
      handler(val, old) {
        if (val) {
          JSON.stringify(val) === JSON.stringify(this.formDataOld) ? this.edited = true : this.edited = false
        }
      },
      deep: true
    },
    tableData: {
      handler(val) {
        if (val) {
          JSON.stringify(val) === JSON.stringify(this.tableDataOld) ? this.edited = true : this.edited = false
        }
      },
      deep: true
    }
  },
  mounted() {
    /** 获取主题内容宽度 start*/
    setTimeout(() => {
      this.mainContentWidth = this.$refs.mainContent.$el.offsetWidth
    }, 200)
    const that = this
    window.onresize = () => {
      return (() => {
        that.mainContentWidth = that.$refs.mainContent.$el.offsetWidth
      })()
    }
    /** 获取主题内容宽度 end*/

    // 单位类型
    this.getWorkloadUnitOptions()
    // 时间偏差单位
    this.getDicts('sys-exception-time').then(res => {
      this.timeOptions = res.data.rows
    })
    // 速度偏差单位
    this.getDicts('sys_exception_speed').then(res => {
      this.speedOptions = res.data.rows
    })
    // 位置偏差
    this.getDicts('sys-exception-position').then(res => {
      this.locationOptions = res.data.rows
    })
    this.speedConfig()
  },
  methods: {
    // 单位类型
    async getWorkloadUnitOptions() {
      const { data: { rows }} = await getSysDicts('sys_exception_speed')
      if (rows) this.workloadUnitOptions = rows
    },
    // 编辑
    handleEdit(row) {
      const isEdit = this.tableData.some(item => item.isEdit)
      if (isEdit) {
        this.msgWarning('请先保存正在编辑的数据')
        return
      }
      // 深拷贝给取消使用
      this.cloneRow = JSON.parse(JSON.stringify(row))
      // 切换编辑状态
      row.isEdit = true
    },
    // 保存
    handleAdd(row) {
      if (row.maxWorkload && row.workloadUnit) {
        row.isEdit = false
      } else {
        this.msgWarning('正在编辑的数据不能为空！')
      }
    },
    // 取消
    handleCancel(index) {
      this.tableData.splice(index, 1, this.cloneRow)
    },
    async speedConfig() {
      const { data: { drillingRigVoList, exceptionInformationSetting }} = await speedConfig()
      // 格式化表格数据为了合并正常显示
      const formatList = []
      drillingRigVoList.forEach(item => {
        item.regionalTypeList.forEach(value => {
          const { workloadUnit, maxWorkload, typeNum: landNum, typeName: landName, id: landId, versionNum } = value
          delete item.regionalTypeList
          formatList.push({ ...item, workloadUnit, maxWorkload, landNum, landName, landId, isEdit: false, versionNum })
        })
      })
      this.tableDataOld = JSON.parse(JSON.stringify(formatList)) // 存储初始数据用于比较是否修改，控制保存按钮
      this.tableData = formatList
      // 将地貌类型拆分合并
      this.spanObj = dataMethod(this.tableData, ['typeName'])
      // 异常设置表单
      this.formDataOld = JSON.parse(JSON.stringify({ ...exceptionInformationSetting })) // 存储初始数据用于比较是否修改，控制保存按钮
      this.formData = { ...exceptionInformationSetting }
      this.getVersionNum()
    },
    // 保存
    handleSave() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          const isEdit = this.tableData.some(item => item.isEdit)
          if (isEdit) {
            this.msgWarning('请先保存正在编辑的数据')
            return
          }
          this.getVersionNum()
          const drillingRigVoList = this.formatTable()
          this.$nextTick(async() => {
            const res = await addException({ drillingRigVoList, exceptionInformationSetting: { ...this.formData }})
            this.msgSuccess(res.message)
          })
        }
      })
    },
    formatTable() {
      // 重复的设备类型
      const repeatList = []
      // 提交数据的表格
      const arr = []
      // 只提交有值的数据
      const saveArr = this.tableData.filter(item => item.workloadUnit)

      saveArr.forEach(item => {
        const { id, typeNum, typeName, workloadUnit, maxWorkload, landNum, landName, landId, versionNum } = item
        // 还原地貌list
        const versionNumNew = versionNum + 1
        const landChild = { typeName: landName, typeNum: landNum, id: landId, workloadUnit, maxWorkload, versionNum: versionNumNew }
        // 判断是否push了相同的设备类型
        if (repeatList.includes(typeNum)) {
          // 存在则查找出相同的设备类型合并地貌
          const index = arr.findIndex(c => c.id === id)
          arr[index].regionalTypeList.push(landChild)
        } else {
          // 不存在则直接添加
          repeatList.push(typeNum)
          arr.push({ id, typeNum, typeName, regionalTypeList: [landChild] })
        }
      })

      return arr
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const _row = this.spanObj[column.property] ? this.spanObj[column.property][rowIndex] : 1
      const _col = _row > 0 ? 1 : 0
      return {
        rowspan: _row,
        colspan: _col
      }
    },
    async getVersionNum() {
      const { data } = await getVersionNum()
      this.formData.versionNum = data + 1
      this.formDataOld.versionNum = data + 1
    }
  }

}

</script>

<style lang="scss">
  .content{
    padding-top: 20px;
  }
  .dataForm {
    margin-top: 30px;
    .el-form-item{
      margin: 0;
      .el-select{
        width: 100%;
      }
    }
  }
  .tips-wap{
    border-left:1px solid #eee;
    text-align: center;
    height: 100%;
    .title{
      font-size: 32px;
      line-height: 40px;
    }
    .info{
      p{
        font-size: 16px;
        line-height: 18px;
      }
    }
    .img{
      width: 50%;
      margin: 0 auto;
      img{
        width: 100%;
        height: auto;
      }
    }
  }
</style>
